package com.holly.unit.bpmn.activiti.ext;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.holly.unit.auth.api.context.LoginContext;
import com.holly.unit.auth.api.pojo.login.LoginUser;
import com.holly.unit.bpmn.activiti.entity.ActivitiZProcess;
import com.holly.unit.bpmn.activiti.mapper.ActivitiZProcessMapper;
import com.holly.unit.bpmn.activiti.pojo.ActProcessRequest;
import com.holly.unit.db.api.factory.PageResultFactory;
import com.holly.unit.db.api.pojo.page.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类描述: 流程节点扩展类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/2/21 15:28
 */
@Service
@Slf4j
public class ActivitiZProcessService extends ServiceImpl<ActivitiZProcessMapper, ActivitiZProcess> {

    @Autowired
    private ActivitiZNodeService zNodeService;

    @Autowired
    private ActivitiZProcessMapper processMapper;


    // 获取流程定义的列表
    public PageResult<ActProcessRequest> actZProcess(Map<String,Object> params) {
        // 参数封装
        List<ActProcessRequest> list = processMapper.selectProcessList(params);
        // 获取当前登录的用户
        LoginUser loginUser = LoginContext.me().getLoginUser();
        // 根据用户名获取角色
        List<String> roleByUserId = zNodeService.queryRoleByAccount(loginUser.getAccount());
        //// 过滤角色
        list = list.stream().filter(p->{
            String roles = p.getRoles();
            if (StrUtil.isBlank(roles)) {
                return true; //未设置授权的所有人都能用
            }else {
                String[] split = roles.split(",");
                for (String role : split) {
                    if (roleByUserId.contains(role)){
                        return true;
                    }
                }
            }
            return false;
        }).collect(Collectors.toList());
        Page<ActProcessRequest> page = new Page<>();
        page.setTotal(list.size()>0?list.size():0);
        Integer pageSize = Convert.toInt(params.get("pageSize"));
        Integer pageNo = Convert.toInt(params.get("pageNo"));
        list=list.subList(pageSize*(pageNo-1),((pageSize*pageNo)>page.getTotal()?Convert.toInt(page.getTotal()):(pageSize*pageNo)));
        page.setRecords(list);
        return PageResultFactory.createPageResult(page);
    }

    /***
     * 根据id查询流程定义上面是否绑定表单
     * true 代表绑定
     * false 没有绑定
     * @param id
     * @return
     */
    public boolean whetherSetUpForm(String id) {
        ActivitiZProcess actProcess = this.getById(id);
        if (ObjectUtil.isEmpty(actProcess)) return false;
        //启动前检查一下 路由等信息是否齐全
        String routeName = actProcess.getRouteName();
        String businessTable = actProcess.getBusinessTable();
        if (StrUtil.isBlank(routeName)||StrUtil.isBlank(businessTable)) return false;
        return true;
    }

    /**
     * 更新最新版本的流程
     * @param processKey
     */
    public void setLatestByProcessKey(String processKey) {
        ActivitiZProcess actProcess = this.findTopByProcessKeyOrderByVersionDesc(processKey);
        if(actProcess==null){
            return;
        }
        actProcess.setLatest(true);
        this.updateById(actProcess);
    }

    /**
     * 通过key设置所有版本为旧
     * @param processKey
     */
    public void setAllOldByProcessKey(String processKey) {
        List<ActivitiZProcess> list = this.list(new LambdaQueryWrapper<ActivitiZProcess>().eq(ActivitiZProcess::getProcessKey,processKey));
        if(list==null||list.size()==0){
            return;
        }
        list.forEach(item -> {
            item.setLatest(false);
        });
        this.updateBatchById(list);
    }

    /******************************************************************************************************************/

    private ActivitiZProcess findTopByProcessKeyOrderByVersionDesc(String processKey) {
        List<ActivitiZProcess> list = this.list(new LambdaQueryWrapper<ActivitiZProcess>().eq(ActivitiZProcess::getProcessKey, processKey)
                .orderByDesc(ActivitiZProcess::getVersion)
        );
        if (CollUtil.isNotEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    /**
     * 构建wrapper
     *
     * @author holly
     * @date 2021/1/13 10:50
     */
    private LambdaQueryWrapper<ActivitiZProcess> createWrapper(Map<String,Object> params) {
        LambdaQueryWrapper<ActivitiZProcess> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.orderByAsc(ActivitiZProcess::getProcessKey).orderByDesc(ActivitiZProcess::getVersion);
        if (ObjectUtil.isEmpty(params)) {
            return queryWrapper;
        }

        String lcmc = String.valueOf(params.get("lcmc"));
        String lckey = String.valueOf(params.get("lckey"));
        String zx = String.valueOf(params.get("zx"));
        String status = String.valueOf(params.get("status"));
        String appId = String.valueOf(params.get("appId"));
        if (StrUtil.isNotBlank(lcmc)){
            queryWrapper.like(ActivitiZProcess::getName, lcmc);
        }
        if (StrUtil.isNotBlank(lckey)){
            queryWrapper.like(ActivitiZProcess::getProcessKey, lckey);
        }
        if (StrUtil.equals(zx,"true")){
            queryWrapper.eq(ActivitiZProcess::getLatest, 1);
        }
        if (StrUtil.isNotBlank(status)){
            queryWrapper.eq(ActivitiZProcess::getStatus, status);
        }
        //关联应用ID
        if (StrUtil.isNotBlank(appId)) {
            queryWrapper.eq(ActivitiZProcess::getAppid, appId);
        }

        return queryWrapper;
    }

}
